<?php

namespace app\job;

use app\core\exception\BusinessException;
use app\core\util\http;
use app\model\Company;
use app\model\CompanyHelp;
use app\model\ZtcUser;
use app\model\Interview;
use think\facade\Db;
use think\facade\Log;
use think\queue\Job;

class SyncZtc
{
    public function companys(Job $job, $data)
    {
        if ($job->attempts() > 2) {
            $job->delete();
            Log::info("expire:companys." . json_encode($data));
            ZtcUser::where('user_id', $data['user_id'])->save(['expire' => 1]);
            return;
        }
        if ($data['info']['expire'] == 1) return;
        // 同步企业数据
        $res = Http::invoke()->request("GET", "http://127.0.0.1:8100/companys?username=" . $data['info']['username'], ['timeout' => 5]);
        $res = json_decode($res, 256);
        $msg = data_get($res, 'msg');
        $code = data_get($res, 'code');
        $resData = data_get($res, 'data');
        if ($msg == '用户已退出，请重新登录') {
            $job->delete();
            ZtcUser::where('user_id', $data['user_id'])->save(['expire' => 1]);
            Log::error('政企直通车账号已失效，请重新验证:companys');
            return;
        }
        if ($res['code'] != 1) {
            Log::error("政企直通车账号返回错误companys，code:$code");
            return;
        }
        if (!$resData) {
            Log::error("政企直通车账号返回错误companys，data");
            return;
        }
        Db::startTrans();
        try {
            $comInfos = Company::where('user_id', $data['user_id'])->field('company_id')->select()->toArray();
            $comIds = array_column($comInfos, 'company_id');
            $resIds = array_column($resData, 'company_id');
            $CompanyLists = Company::where('company_id', 'in', $resIds)->field('company_id')->select()->toArray();
            $CompanyIds = array_column($CompanyLists, 'company_id');
            $CompanyData = [];
            foreach ($resData as $key => $company) {
                if (in_array($company['company_id'], $CompanyIds)) {
                    continue;
                }
                $CompanyData[$key]['user_id'] = $data['user_id'];
                $CompanyData[$key]['company_id'] = $company['company_id'];
                $CompanyData[$key]['leader'] = $company['leader'];
                $CompanyData[$key]['company_name'] = $company['company_name'];
                $CompanyData[$key]['company_code'] = $company['company_code'];
                $CompanyData[$key]['mobiles'] = $company['mobiles'];
                $CompanyData[$key]['area'] = $company['area'];
                $CompanyData[$key]['visit_num'] = $company['visit_num'];
            }
            Log::info("comInfos:" . json_encode($comInfos));
            $w = [];
            $w[] = ['user_id', '=', 1];//绑定到超级管理员的走访记录数据删除重新绑定
            $w[] = ['company_id', 'in', $resIds];
            if ($data['user_id'] != 1) {
                (new Company())::where($w)->update(['user_id' => $data['user_id']]);
            }
            $insIds = array_diff($resIds, $comIds);
            $resFilArr = array_reduce($CompanyData, function ($pushArr, $item) use ($insIds) {
                if (in_array($item['company_id'], $insIds)) {
                    $pushArr['ins'][] = $item;
                } else {
                    $pushArr['upd'][] = $item;
                }
                return $pushArr;
            }, []);
            $resFilArr['del'] = array_diff($comIds, $resIds);
            Log::info(json_encode($resIds) . ":" . json_encode($comIds) . ":" . json_encode($insIds) . ":" . json_encode($resFilArr['del']));
            Log::info("resFilArr:" . json_encode($resFilArr));
            if (!empty($resFilArr['ins'])) {
                (new Company())->insertAll($resFilArr['ins']);
            }
            if (!empty($resFilArr['upd'])) {
                (new Company())->saveAll($resFilArr['upd']);
            }
            if (!empty($resFilArr['del'])) {
                (new Company())->where('id', 'in', $resFilArr['del'])->delete();
            }
            $job->delete();
            Db::commit();
        } catch (\Exception $e) {
            Log::info($e->getMessage());
            Log::info($e->getLine());
            Db::rollback();
        }
    }

    public function visits(Job $job, $data)
    {
        if ($job->attempts() > 2) {
            $job->delete();
            Log::info("expire:visits." . json_encode($data));
            ZtcUser::where('user_id', $data['user_id'])->save(['expire' => 1]);
            return;
        }
        if ($data['info']['expire'] == 1) return;
        $res = Http::invoke()->request("GET", "http://127.0.0.1:8100/visits?username=" . $data['info']['username'], ['timeout' => 5]);
        if ($res) $res = json_decode($res, 256);
        $msg = data_get($res, 'msg');
        $code = data_get($res, 'code');
        $listData = data_get($res, 'data');
        if ($msg == '用户已退出，请重新登录') {
            $job->delete();
            ZtcUser::where('user_id', $data['user_id'])->save(['expire' => 1]);
            Log::error('政企直通车账号已失效，请重新验证:visits');
            return;
        }
        if ($res['code'] != 1) {
            Log::error("政企直通车账号返回错误visits，code:$code");
            return;
        }
        if (!$listData) {
            Log::error("政企直通车账号返回错误visits，data");
            return;
        }
        Log::info("expire:listData." . json_encode($listData));
        Db::startTrans();
        try {
            $visIds = array_column($listData, 'id');
            $InterviewLists = Interview::where('id', 'in', $visIds)->field('id')->select()->toArray();
            $InterviewIds = array_column($InterviewLists, 'id');
            $visData = $HelpArr = $interview_ids = [];
            foreach ($listData as $key => $value) {
                if (in_array($value['id'], $InterviewIds)) {
                    continue;
                }
                $visData[$key]['id'] = $value['id'];
                $visData[$key]['user_id'] = $data['user_id'];
                $visData[$key]['area'] = $value['area'];
                $visData[$key]['party_situation'] = $value['party_situation'];
                $visData[$key]['wo_title'] = $value['wo_title'];
                $visData[$key]['wo_status'] = $value['wo_status'];
                $visData[$key]['sys_user_id'] = $value['sys_user_id'];
                $visData[$key]['wo_id'] = $value['wo_id'];
                $visData[$key]['site_code'] = $value['site_code'];
                $visData[$key]['record_time'] = $value['record_time'];
                $visData[$key]['record_pic'] = $value['record_pic'];
                $visData[$key]['qh_code'] = $value['qh_code'];
                $visData[$key]['platform_order_code'] = $value['platform_order_code'];
                $visData[$key]['name'] = $value['name'];
                $visData[$key]['link_phone'] = $value['link_phone'];
                $visData[$key]['leaders'] = $value['leaders'];
                $visData[$key]['lead_name'] = $value['lead_name'];
                $visData[$key]['lead_company_id'] = $value['lead_company_id'];
//                $visData[$key]['evaluate_score'] = $value['evaluate_score'];
//                $visData[$key]['evaluate_content'] = $value['evaluate_content'];
                $visData[$key]['deal_type'] = $value['deal_type'];
                $visData[$key]['detail'] = $value['detail'];
                $visData[$key]['deal_content'] = $value['deal_content'];
                $visData[$key]['credit_code'] = $value['credit_code'];
                $visData[$key]['order_code'] = $value['order_code'];
                $visData[$key]['wo_create_time'] = $value['wo_create_time'];
                $interview_ids[] = $value['id'];
                $HelpArr[] = [
                    'user_id' => $data['user_id'] ?? "",
                    'company_id' => $value['lead_company_id'] ?? "",
                    'interview_id' => $value['id'] ?? "",
                    'help_time' => $value['record_time'] ?? "",
                    'update_time' => $value['record_time'] ?? "",
                    'create_time' => $value['record_time'] ?? "",
                    'lat' => '',
                    'lng' => '',
                    'address' => '',
                ];
            }

            $intInfos = Interview::where('user_id', $data['user_id'])->field('id')->select()->toArray();
            $w = [];
            $w[] = ['user_id', '=', 1];//绑定到超级管理员的走访记录数据删除重新绑定
            $w[] = ['id', 'in', $visIds];
            if ($data['user_id'] != 1) {
                (new Interview())::where($w)->update(['user_id' => $data['user_id']]);
            }
            $intIds = array_column($intInfos, 'id');
            $insIds = array_diff($visIds, $intIds);
            $visFilArr = array_reduce($visData, function ($pushArr, $item) use ($insIds) {
                if (in_array($item['id'], $insIds)) {
                    $pushArr['ins'][] = $item;
                } else {
                    $pushArr['upd'][] = $item;
                }
                return $pushArr;
            }, []);
            $visFilArr['del'] = array_diff($intIds, $visIds);
            Log::info("visIds" . json_encode($visIds));
            Log::info("intIds" . json_encode($intIds));
            Log::info("insIds" . json_encode($insIds));
            Log::info("delIds" . json_encode($visFilArr['del']));
            Log::info("visFilArr:" . json_encode($visFilArr));
            if (!empty($visFilArr['ins'])) {
                (new Interview())->insertAll($visFilArr['ins']);
            }
            if (!empty($HelpArr)) {
                (new CompanyHelp())->where('interview_id', 'in', $interview_ids)->delete();
                (new CompanyHelp())->insertAll($HelpArr);
            }
            if (!empty($visFilArr['upd'])) {
                (new Interview())->saveAll($visFilArr['upd']);
            }
            if (!empty($visFilArr['del'])) {
                (new Interview())->where('id', 'in', $visFilArr['del'])->delete();
            }
            Db::commit();
        } catch (\Exception $e) {
            Log::info($e->getMessage());
            Log::info($e->getLine());
            Db::rollback();
        }
    }

    public function visitsComment(Job $job, $data)
    {
        if ($job->attempts() > 2) {
            $job->delete();
            Log::info("expire:visitsComment." . json_encode($data));
            ZtcUser::where('user_id', $data['user_id'])->save(['expire' => 1]);
            return;
        }
        if ($data['info']['expire'] == 1) return;
        $Http_util = Http::invoke();
        // 同步走访数据
        $res = $Http_util->request("GET", "http://127.0.0.1:8100/visit_comment?username=" . $data['info']['username'], ['timeout' => 5]);
        Log::info("visit_comment : $res");
        if ($res) $res = json_decode($res, 256);
        $code = data_get($res, 'code');
        $resData = data_get($res, 'data');
        $msg = data_get($res, 'msg');
        if ($msg == '用户已退出，请重新登录') {
            $job->delete();
            ZtcUser::where('user_id', $data['user_id'])->save(['expire' => 1]);
            Log::error('政企直通车账号已失效，请重新验证:visit_comment' . $job->attempts());
            return;
        }
        if ($code == '') return;
        if ($code != 1) {
            Log::error("政企直通车账号返回错误:visit_comment:$code:" . $job->attempts());
        } else {
            if ($resData) {
                (new Interview())->saveAll($resData);
            }
            $job->delete();
        }
    }
}